package com.promis.okhttp;

import com.promis.util.CollectionUtils;
import com.promis.util.DateUtils;
import com.promis.util.StringUtils;

import java.io.File;
import java.util.Date;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by jidanbo on 2018/1/24.
 */

public class HttpFileParams {

    public static final MediaType STREAM = MediaType.parse("application/octet-stream");
    private MultipartBody.Builder builder;

    public HttpFileParams() {
        builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
    }

    public void add(String key, String fileName, File file) {
        if (file != null && file.exists()) {
            fileName = fileName == null ? "" : fileName;
            builder.addFormDataPart(key, fileName, RequestBody.create(STREAM, file));
        }
    }

    public void add(String key, String fileName, byte[] data) {
        if (data != null && data.length > 0) {
            fileName = fileName == null ? "" : fileName;
            builder.addFormDataPart(key, fileName, RequestBody.create(STREAM, data));
        }
    }

    public void add(String key, String value) {
        if (!StringUtils.isNullOrEmpty(value)) {
            builder.addFormDataPart(key, value);
        }
    }

    public void add(String key, String[] values) {
        if (!CollectionUtils.isNullOrEmpty(values)) {
            for (String value : values) {
                if (!StringUtils.isNullOrEmpty(value)) {
                    builder.addFormDataPart(key, value);
                }
            }
        }
    }

    public void add(String key, Number value) {
        if (value != null) {
            builder.addFormDataPart(key, value.toString());
        }
    }

    public void add(String key, Number[] values) {
        if (!CollectionUtils.isNullOrEmpty(values)) {
            for (Number value : values) {
                if (value != null) {
                    builder.addFormDataPart(key, value.toString());
                }
            }
        }
    }

    public void add(String key, Boolean value) {
        if (value != null) {
            builder.addFormDataPart(key, value.toString());
        }
    }

    public void add(String key, Boolean[] values) {
        if (!CollectionUtils.isNullOrEmpty(values)) {
            for (Boolean value : values) {
                if (value != null) {
                    builder.addFormDataPart(key, value.toString());
                }
            }
        }
    }

    public void add(String key, Date value) {
        if (value != null) {
            builder.addFormDataPart(key, DateUtils.format(value));
        }
    }

    public MultipartBody.Builder getBuilder() {
        return builder;
    }
}
